const db = wx.cloud.database()
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    name: '',
    studentid: '',
    tel: '',
    imgurl: '' //云存储的头像
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**获取姓名 */
    name(e) {
      this.setData({
        name: e.detail.value
      })
    },
    /**获取学号 */
    studentid(e) {
      this.setData({
        studentid: e.detail.value
      })
    },
    /**获取电话 */
    tel(e) {
      this.setData({
        tel: e.detail.value
      })
    },
    /**上传头像 */
    upload() {
      let that = this;
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          wx.cloud.uploadFile({
            cloudPath: new Date().getTime() + "." + res.tempFiles[0].tempFilePath.split(".")[1],
            filePath: res.tempFiles[0].tempFilePath,
          }).then(res => {
            that.setData({
              imgurl: res.fileID
            })
          }).catch()
        }
      })
    },
    save() {
      let openid = wx.getStorageSync('openid');
      db.collection("userlist").where({
        _openid: openid
      }).then(res=>{
        
      })
        //如果已经有该用户，则更新
        
        db.collection("userlist").where({
          _openid: openid
        }).update({
          data: {
            photo: this.data.imgurl,
            name: this.data.name,
            tel: this.data.tel,
            studentid: this.data.studentid,
          }
        }).then(res => {
          wx.showToast({
            title: '更新成功',
          })
        })
     
      wx.showLoading({
        title: "登录中",
        mask: true
      }),
      db.collection("userlist").add({
        data: {
          photo: this.data.imgurl,
          name: this.data.name,
          studentid: this.data.studentid,
          tel: this.data.tel,
        }
      }).then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '信息已经保存成功',
        })
      }) },
    },


  /**
   * 生命周期函数-组件被调用
   */
  attached() {
    let name = wx.getStorageSync('name');
    let studentid = wx.getStorageSync('studentid');
    let tel = wx.getStorageSync('tel');
    let imgurl = wx.getStorageSync('imgurl');
    this.setData({
      name,studentid,tel,imgurl
    })
  },
})